package com.bdqn.servlet.index;

import com.bdqn.pojo.SysUser;
import com.bdqn.service.SysUserService;
import com.bdqn.service.impl.SysUserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * LoginServlet
 *
 * @author LILIBO
 * @since 2024/7/3
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    /**
     * 引入业务逻辑层
     */
    private final SysUserService sysUserService = new SysUserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("jsp/login.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取页面传递的参数
        String account = request.getParameter("account");
        String password = request.getParameter("password");
        // 调用业务逻辑层完成登录验证
        SysUser loginUser = sysUserService.login(account, password);
        if (loginUser == null) {
            request.setAttribute("error", "账号或密码错误，请重新登录");
            request.getRequestDispatcher("jsp/login.jsp").forward(request, response);
            return;
        }
        // 将登录用户信息设置到Session
        request.getSession().setAttribute("userSession", loginUser);
        response.sendRedirect("frame");
    }

}
